import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    userRole: localStorage.getItem('userRole') || '',
    isLoggedIn: !!localStorage.getItem('token'),
    userInfo: null
  }),
  actions: {
    // 登录
    login(token, role = 'user') {
      this.token = token
      this.userRole = role
      this.isLoggedIn = true
      localStorage.setItem('token', token)
      localStorage.setItem('userRole', role)
    },
    // 退出登录
    logout() {
      this.token = ''
      this.userRole = ''
      this.isLoggedIn = false
      this.userInfo = null
      localStorage.removeItem('token')
      localStorage.removeItem('userRole')
    },
    // 清除用户信息
    clearUserInfo() {
      this.logout()
    },
    // 设置用户信息
    setUserInfo(info) {
      this.userInfo = info
    }
  }
})
